package com.kuangstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuangstudy.entity.State;
import com.kuangstudy.entity.StateDetail;
import com.kuangstudy.service.StateDetailService;
import com.kuangstudy.service.StateService;
import com.kuangstudy.vo.R;
import com.kuangstudy.vo.StateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @program: ksd-state
 * @description:
 * @author: 陈恩涛
 * @create: 2021-05-08 17:16
 **/

@Controller
public class StateController {

    @Autowired
    private StateService stateService;

    @Autowired
    private StateDetailService stateDetailService;

    /**
     * 根据id跳转到具体的统计明细页面
     * @param id
     * @param modelMap
     * @return
     */
    @GetMapping("/state/{id}")
    public String findState(@PathVariable("id") Integer id, ModelMap modelMap) {
        // 1、根据id查询统计是否存在
        State state = stateService.getById(id);
        if (state != null) {
            //2、如果存在就进入页面
            modelMap.put("id", id);
            return "state/detail";
        }
        //3、如果不存在就进入错误页面（统一异常处理和错误处理）
        return "redirect:/error";
    }

    /**
     *方法描述： 根据stateId查询统计和统计明细
     *
     * @param stateId
     * @return com.kuangstudy.vo.R
     * @author chenentao
     * @date 2021/5/11 10:12
     */
    @GetMapping("/state/detail")
    @ResponseBody
    public R getStateDetail(Integer stateId) {

        //1、根据stateId查询统计
        if (StringUtils.isEmpty(stateId)) {
            return R.error().code(601).message("没用找到对应的统计！");
        }
        State state = stateService.getById(stateId);
        if (state == null) {
            return R.error().code(601).message("没用找到对应的统计！");
        }

        //2、根据stateId查询统计明细
        QueryWrapper<StateDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stateid",stateId);
        List<StateDetail> stateDetailList = stateDetailService.list(queryWrapper);

        //3、把State对象和StateDetail组装到Vo对象
        StateVo stateVo = new StateVo();
        BeanUtils.copyProperties(state, stateVo);
        stateVo.setStateDetailList(stateDetailList);

        //4、然后把Vo用R统一返回出去
        return R.ok().data("stateVo",stateVo);
    }

    @GetMapping("/state/saveupdate")
    public R saveState() {
        State state = new State();
        state.setId(2);
        state.setTitle("xxs");
        return stateService.saveOrUpdate(state)?R.ok():R.error();
    }
}
